package com.zhxs.nfcscan;

import android.Manifest;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Build;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.http.EasyHttp;
import com.tencent.mmkv.MMKV;
import com.zhhd.base.BaseDialog;
import com.zhxs.nfcscan.base.app.AppActivity;
import com.zhxs.nfcscan.base.app.AppApplication;
import com.zhxs.nfcscan.base.dialog.CommonDialog;
import com.zhxs.nfcscan.base.dialog.MessageDialog;
import com.zhxs.nfcscan.base.dialog.ReadCardDialog;
import com.zhxs.nfcscan.base.dialog.TipsDialog;
import com.zhxs.nfcscan.base.dialog.TitleDialog;
import com.zhxs.nfcscan.base.http.api.RtmpurlsApi;
import com.zhxs.nfcscan.base.http.entity.PersonInfo;
import com.zhxs.nfcscan.utils.NFCTools;
import com.zhxs.nfcscan.utils.NFCUtil;
import com.zhxs.nfcscan.utils.NfcMessageParser;
import com.zhxs.nfcscan.view.CardTestActivity;
import com.zhxs.nfcscan.view.DataSyncActivity;
import com.zhxs.nfcscan.view.PatrolActivity;
import com.zhxs.nfcscan.view.SettingsActivity;
import com.zhxs.utils.LogUtil;
import com.zhxs.websocket.RequestData;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;

public class LogicActivity extends AppActivity {
    private static final int REQUEST_CODE_NFC_PERMISSION = 0x12345678;
    private Tag tag;

    // UI组件
    private LinearLayout layoutPatrol;
    private LinearLayout layoutSync;
    private LinearLayout layoutSettings;
    private LinearLayout layoutCardTest;
    private View btnBindDevice;
    private TextView tvVersion;

    // 持机人信息UI组件
    private LinearLayout layoutPersonInfo;
    private TextView tvPersonName;
    private TextView tvPersonDept;
    private TextView tvPersonGroup;

    // 状态变量
    private boolean isDeviceBound = false;
    private NfcAdapter nfcAdapter;
    private MMKV mmkv;

    /**
     * 用于绑定用户的卡号
     */
    private String currentCardId;

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent(LogicActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(LogicActivity.this, 0, intent, 0);
        nfcAdapter.enableForegroundDispatch(LogicActivity.this, pendingIntent, null, null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        nfcAdapter.disableForegroundDispatch(LogicActivity.this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_logic;
    }

    @Override
    protected void initView() {
        // 初始化UI组件
        layoutPatrol = findViewById(R.id.layout_patrol);
        layoutSync = findViewById(R.id.layout_sync);
        layoutSettings = findViewById(R.id.layout_settings);
        layoutCardTest = findViewById(R.id.layout_card_test);
        btnBindDevice = findViewById(R.id.btn_bind_device);
        tvVersion = findViewById(R.id.tv_version);

        // 初始化持机人信息UI组件
        layoutPersonInfo = findViewById(R.id.layout_person_info);
        tvPersonName = findViewById(R.id.tv_person_name);
        tvPersonDept = findViewById(R.id.tv_person_dept);
        tvPersonGroup = findViewById(R.id.tv_person_group);

        // 设置点击监听器
        layoutPatrol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPatrolClick();
            }
        });

        layoutSync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSyncClick();
            }
        });

        layoutSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LogicActivity.this, SettingsActivity.class);
                startActivity(intent);
            }
        });

        layoutCardTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCardTestClick();
            }
        });

        btnBindDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBindDeviceClick();
            }
        });



    }

    @Override
    protected void initData() {
        checkPermission();
        mmkv = MMKV.defaultMMKV();
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        // 设置版本号
        setAppVersion();
        // 检查是否已有绑定的持机人信息
        checkBoundPersonInfo();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.d("===========读到的卡信息==========");
        processTag(intent);
    }

    private void processTag(Intent intent) {
        tag = NFCTools.Companion.getNFCTagFromIntent(intent);
        if (tag == null){
            return;
        }
        // 获取标签id数组
        byte[] bytesId = tag.getId();
        // 显示NFC读取结果
        showNfcResult(bytesId);
    }

    /**
     * 显示NFC读取结果
     */
    private void showNfcResult(byte[] bytesId) {
        String cardId = NfcMessageParser.bytesToHexString(bytesId,false);
        LogUtil.d("读到的卡信息："+ cardId);

        // 显示详细信息对话框
        new TitleDialog.Builder(this)
                .setTitle("卡号："+cardId)
                .show();

        currentCardId = cardId;
    }


    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.NFC) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.NFC)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示")
                        .setMessage("需要Nfc权限才能正常使用此功能")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(LogicActivity.this, new String[]{Manifest.permission.NFC}, REQUEST_CODE_NFC_PERMISSION);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(LogicActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .create().show();

            } else {
                ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.NFC }, REQUEST_CODE_NFC_PERMISSION);
            }
        }

        //检查是否已经授予权限，大于6.0的系统适用，小于6.0系统默认打开，无需理会
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
//            //没有权限，须要申请权限，由于是打开一个受权页面，因此拿不到返回状态的，因此建议是在onResume方法中重新执行一次校验
//            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
//            intent.setData(Uri.parse("package:" + getPackageName()));
//            startActivity(intent);
//        }
    }

    /**
     * 巡更功能点击
     */
    private void onPatrolClick() {
        if (!isDeviceBound) {
            Toast.makeText(this, "请先绑定持机人", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(LogicActivity.this, PatrolActivity.class);
        startActivity(intent);

    }

    /**
     * 数据同步功能点击
     */
    private void onSyncClick() {
        Intent intent = new Intent(LogicActivity.this, DataSyncActivity.class);
        startActivity(intent);
    }

    /**
     * 刷卡测试功能点击
     */
    private void onCardTestClick() {
        Intent intent = new Intent(LogicActivity.this, CardTestActivity.class);
        startActivity(intent);
    }

    /**
     * 绑定持机人功能点击
     */
    private void onBindDeviceClick() {
        if (isDeviceBound) {
            // 显示解绑对话框
            new MessageDialog.Builder(this)
                    .setTitle("解绑持机人")
                    .setMessage("确定要解绑当前持机人吗？")
                    .setListener(new MessageDialog.OnListener() {
                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            isDeviceBound = false;
                            // 隐藏持机人信息
                            hidePersonInfo();
                            //将本地人员信息删除
                            mmkv.remove(AppApplication.KEY_PERSON_INFO);

                            Toast.makeText(LogicActivity.this, "解绑成功", Toast.LENGTH_SHORT).show();
                            // 更新按钮文本
                            if (btnBindDevice instanceof android.widget.Button) {
                                ((android.widget.Button) btnBindDevice).setText(getString(R.string.bind_handheld_device));
                            }
                        }
                    }).show();

        } else {
            if (TextUtils.isEmpty(currentCardId)){
                new TitleDialog.Builder(this)
                        .setTitle("请先进行读卡")
                        .show();
//                Toast.makeText(LogicActivity.this, "请先进行读卡", Toast.LENGTH_SHORT).show();
                return;
            }
            String json = mmkv.decodeString(AppApplication.KEY_PERSON_LIST_INFO, "");
            if (TextUtils.isEmpty(json)){
                new TitleDialog.Builder(this)
                        .setTitle("暂无本地人员信息\n    请先同步数据")
                        .show();
//                Toast.makeText(LogicActivity.this, "暂无本地人员信息，请先同步数据", Toast.LENGTH_SHORT).show();
                return;
            }
            List<PersonInfo> personInfos = new Gson().fromJson(json, new TypeToken<List<PersonInfo>>(){}.getType());
            if (personInfos!=null && !personInfos.isEmpty()){
                for (int i =0 ;i<personInfos.size();i++){
                    if (TextUtils.isEmpty(personInfos.get(i).getRfidCardId())){
                        //人员信息里没有卡号 防止死机
                        continue;
                    }
                    if (currentCardId.toLowerCase().equals(personInfos.get(i).getRfidCardId().toLowerCase())){
                        PersonInfo personInfo = personInfos.get(i);

                        // 显示持机人信息
                        showPersonInfo(personInfo);

                        mmkv.putString(AppApplication.KEY_PERSON_INFO, new Gson().toJson(personInfo));
                        Toast.makeText(LogicActivity.this, "人员信息绑定成功！", Toast.LENGTH_SHORT).show();
                        isDeviceBound = true;
                        // 更新按钮文本
                        if (btnBindDevice instanceof android.widget.Button) {
                            ((android.widget.Button) btnBindDevice).setText("解绑持机人");
                        }
                    }
                }
            }
            if (!isDeviceBound){
                new TipsDialog.Builder(this)
                        .setMessage("暂无本地人员信息，请先同步数据")
                        .show();
//                Toast.makeText(LogicActivity.this, "暂无本地人员信息，请先同步数据", Toast.LENGTH_SHORT).show();
            }
            //若List没数据 则提示 暂无本地人员信息，请先同步数据
//            new ReadCardDialog.Builder(this)
//                    .setMessage("等待读卡中。。。")
//                    .addOnShowListener(new BaseDialog.OnShowListener() {
//                        @Override
//                        public void onShow(BaseDialog dialog) {
//                            LogUtil.d("ReadCardDialog onShow：");
//                            Intent intent = new Intent(LogicActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                            PendingIntent pendingIntent = PendingIntent.getActivity(LogicActivity.this, 0, intent, 0);
//                            nfcAdapter.enableForegroundDispatch(LogicActivity.this, pendingIntent, null, null);
//                        }
//                    }).addOnDismissListener(new BaseDialog.OnDismissListener() {
//                        @Override
//                        public void onDismiss(BaseDialog dialog) {
//                            LogUtil.d("ReadCardDialog onDismiss：");
//                            nfcAdapter.disableForegroundDispatch(LogicActivity.this);
//                        }
//                    })
//                    .show();
            // 绑定持机人
//            new AlertDialog.Builder(this)
//                    .setTitle("绑定持机人")
//                    .setMessage("请输入持机人信息")
//                    .setPositiveButton(getString(R.string.common_confirm), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            isDeviceBound = true;
//                            Toast.makeText(LogicActivity.this, getString(R.string.bind_success), Toast.LENGTH_SHORT).show();
//                            // 更新按钮文本
//                            if (btnBindDevice instanceof android.widget.Button) {
//                                ((android.widget.Button) btnBindDevice).setText("解绑持机人");
//                            }
//                        }
//                    })
//                    .setNegativeButton(getString(R.string.common_cancel), null);
        }
    }

    /**
     * 显示持机人信息
     */
    private void showPersonInfo(PersonInfo personInfo) {
        tvPersonName.setText("姓名：" + personInfo.getUserName());
        tvPersonDept.setText("部门：" + personInfo.getDeptName());
        //添加过滤 没有就不显示
        if (TextUtils.isEmpty(personInfo.getDeptGroupName())){
            tvPersonGroup.setVisibility(View.GONE);
        }else {
            tvPersonGroup.setText("组别：" + personInfo.getDeptGroupName());
        }

        layoutPersonInfo.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏持机人信息
     */
    private void hidePersonInfo() {
        layoutPersonInfo.setVisibility(View.GONE);
    }

    /**
     * 检查是否已有绑定的持机人信息
     */
    private void checkBoundPersonInfo() {
        String userInfoJson = mmkv.decodeString(AppApplication.KEY_PERSON_INFO, "");
        if (!TextUtils.isEmpty(userInfoJson)) {
            try {
                PersonInfo personInfo = new Gson().fromJson(userInfoJson, PersonInfo.class);
                if (personInfo != null) {
                    showPersonInfo(personInfo);
                    isDeviceBound = true;
                    // 更新按钮文本
                    if (btnBindDevice instanceof android.widget.Button) {
                        ((android.widget.Button) btnBindDevice).setText("解绑持机人");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置应用版本号
     */
    private void setAppVersion() {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            String versionName = packageInfo.versionName;
            int versionCode = packageInfo.versionCode;
            String versionText = "Version: v" + versionName;
            tvVersion.setText(versionText);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            // 如果获取失败，使用默认版本号
            tvVersion.setText(getString(R.string.version_info));
        }
    }

}
